package org.easy.bytefaceswap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.net.URI;
import java.util.HashMap;

@Slf4j
public class FaceSwapTemplate {

    private static String requestUrl = "https://visual.volcengineapi.com?Action=CVProcess&Version=2022-08-31";
    private static String requestKey = "face_swap3_6";

    private FaceSwapClient signerClient;

    public FaceSwapTemplate(FaceSwapClient signerClient) {
        this.signerClient = signerClient;
    }

    public String faceSwap(String faceImg, String needReplacedImage) {
        try {
            /* create signer */
            Signer signer = new Signer();

            /* create http client */
            CloseableHttpClient httpClient = HttpClients.createDefault();

            /* prepare request */
            HttpPost request = new HttpPost();
            request.setURI(new URI(requestUrl));


            HashMap<String, Object> params = new HashMap<>();
            params.put("req_key", requestKey);
            params.put("image_urls", new String[]{faceImg
                    , needReplacedImage});
            params.put("return_url", true);

            HttpEntity http = new StringEntity(JSON.toJSONString(params));
            request.setEntity(http);

            signer.sign(request, signerClient);
            /* launch request */
            CloseableHttpResponse response = httpClient.execute(request);

            /* get response body */
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                JSONObject jsonObject = JSON.parseObject(result);
                if (CollectionUtils.isEmpty(jsonObject.getJSONObject("data").getJSONArray("binary_data_base64"))&&CollectionUtils.isEmpty(jsonObject.getJSONObject("data").getJSONArray("image_urls"))) {
                    return null;
                } else {
                    return jsonObject.getJSONObject("data")
                            .getJSONArray("image_urls").getString(0);
                }
            }
            /* close resources */
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getBase64Image(String base64Image) {
        // 检查是否有数据类型声明部分（如data:image/png;base64,），有的话需要去除它获取真正的Base64编码数据
        if (base64Image.contains(",")) {
            base64Image = base64Image.split(",")[1];
        }
        return base64Image;
    }
}
